define([
    'jquery',
    'underscore',
    'backbone',
    'text!template/topic/topic_item.html',
    'collection/topic/topic',
    'collection/topic/topic_application',
    'bootstrap'
], function(
    $,
    _,
    Backbone,
    ItemTemplate,
    TopicCollection,
    TopicAppCollection,
    require
){

    var App = Backbone.View.extend({
        el: '#page-topic',
        template: _.template(ItemTemplate),

        initialize: function() {
            this.render();
        },

        render: function() {
            var _this = this;

            var topicCollection = new TopicCollection();
            topicCollection.fetch({
                success: function(topics) {
                    var topicsData = topics.toJSON();

                    for (var i=0; i<topicsData.length; i++) {
                        // render after the data received
                        var _apps = _this.app_restore(topicsData[i].id);
                        
                        _this.$el.find('[bb-container]').append(_this.template({
                            topic_cover: topicsData[i].topic_cover,
                            name: topicsData[i].name,
                            topic_graphic: topicsData[i].topic_graphic,
                            topic_link: topicsData[i].topic_link,
                            graphic_de_waver: topicsData[i].graphic_de_waver,
                            frontend_de_waver: topicsData[i].frontend_de_waver,
                            post_time: topicsData[i].post_time,
                            channel_waver: topicsData[i].channel_waver,
                            apps: _apps
                        }));
                    }
                }
            });
        },

        app_restore: function(topic_id) {
            var _this = this;
            var topicAppCollection = new TopicAppCollection();
            var _apps = new Array();

            topicAppCollection.fetch({
                async: false,
                success: function(relas) {
                    var relasData = relas.toJSON();
                    for (var i=0; i<relasData.length; i++) {
                        if (relasData[i]['topic_id'] == topic_id) {
                            _apps.push(relasData[i]['application_waver']);
                        }
                    }
                }
            });
            return _apps;
        }
    });

    new App();
});
